#include "data_transfer.h"
const char *g_ttyName = "/dev/ttySAC0";

data_transfer::data_transfer()
	:fd(-1)
{
	init();
}

data_transfer::~data_transfer()
{
	if(fd > 0)
	{
		close(fd);
		fd = -1;
	}
}

//initialize
void data_transfer::init()
{
	struct termios options;

	//open the port
	//The O_NOCTTY flag tells UNIX that this program doesn't 
	//want to be the "controlling terminal" for that port
	fd = open(g_ttyName,O_RDWR | O_NOCTTY);
	//Could not open the port
	if(fd == -1)
		return;

	//get the current options for the port
	tcgetattr(fd, &options);

	//set the baud rates to 57600
	cfsetispeed(&options, B57600);
	cfsetospeed(&options, B57600);

	//Enable the receiver and set local mode
	//The c_cflag member contains two options that should always
	//be enabled, CLOCAL and CREAD. These will ensure that your 
	//program does not become the 'owner' of the port subject to 
	//sporatic job control and hangup signals, and also that the 
	//serial interface driver will read incoming data bytes.
	options.c_cflag |= (CLOCAL | CREAD);

	//set the character size
	options.c_cflag &= ~CSIZE; /* Mask the character size bits */
	options.c_cflag |= CS8;    /* Select 8 data bits */

	//set parity checking
	//No parity
	options.c_cflag &= ~PARENB;
	options.c_cflag &= ~CSTOPB;

	//set local options
	//choose raw input
	//Raw input is unprocessed. Input characters are passed through 
	//exactly as they are received, when they are received
	options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
	//choosing raw output
	options.c_oflag &= ~OPOST;

	options.c_cc[VTIME] = 50; /* set timeout=5 seconds*/   
	options.c_cc[VMIN] = 0;

	//Set the new options for the port
	tcsetattr(fd, TCSANOW, &options);
}

//if tty is open,return true;else return false
bool data_transfer::is_open()
{
	if(fd == -1)
		return false;
	else
		return true;
}

int data_transfer::sendTty(unsigned char *pbuf,int size)
{
	if(fd == -1)
		return -1;

	//send data
	return write(fd,pbuf,size);
}

int data_transfer::recvTty(unsigned char *pbuf,int size)
{
	if(fd == -1)
		return -1;
	//recv data
	//If no characters are available,read() will block (wait) until 
	//characters come in, an interval timer expires,or an error occurs
	return read(fd,pbuf,size);
}

//clear the input buffer
void data_transfer::flush()
{
	tcflush(fd,TCIFLUSH);
}
